﻿using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HookupAppForm
{
    public partial class FormUser : Form
    {
        private string url = "api/services/app/User/";
        private UserDto Item { get; set; }
        private APIClient Client { get; set; }
        public FormUser(UserDto item, APIClient _client)
        {
            InitializeComponent();
            Item = item;
            Client = _client;
        }

        private void FormUser_Load(object sender, EventArgs e)
        {
            GetRoles();
            LoadData();
            saveToolStripButton.Enabled = Item != null;
            copyToolStripButton.Enabled = Item != null;
        }
        private void LoadData()
        {
            string act = string.Format(url + "GetAll?SkipCount=0&MaxResultCount=999");
            var result = Client.Get(act);
            if (Utils.ExceptionHandler(result) == null)
            {
                ItemsDto<UserDto> res = JsonConvert.DeserializeObject<ItemsDto<UserDto>>(result);
                dataGridViewM.DataSource = res.result.items;
                FromSetting[] fromSettings = new FromSetting[7];
                fromSettings[0] = new FromSetting { FieldDisplay = "编号" };
                fromSettings[1] = new FromSetting { FieldDisplay = "用户名" };
                fromSettings[2] = new FromSetting { FieldDisplay = "名" };
                fromSettings[3] = new FromSetting { FieldDisplay = "姓" };
                fromSettings[4] = new FromSetting { FieldDisplay = "邮箱", FieldWidth = 120 };
                fromSettings[5] = new FromSetting { FieldDisplay = "激活", FieldWidth = 55 };
                Utils.SetHeader(dataGridViewM, fromSettings);
            }
        }

        private void GetRoles()
        {
            string act = string.Format(url + "GetRoles");
            var result = Client.Get(act);
            if (Utils.ExceptionHandler(result) == null)
            {
                ItemsDto<RoleDto> res = JsonConvert.DeserializeObject<ItemsDto<RoleDto>>(result);
                dataGridViewM.DataSource = res.result.items;
                foreach (var item in res.result.items)
                {
                    cListBoxRoleNames.Items.Add(item.Name, false);
                }
            }
            
        }

        private void SaveToolStripButton_Click(object sender, EventArgs e)
        {
            string act = Item == null ? "Create" : "Update";
            string result = string.Empty;
            List<string> selectRoles = new List<string>();
            for (int i = 0; i < cListBoxRoleNames.Items.Count; i++)
            {
                if (cListBoxRoleNames.GetItemChecked(i))
                {
                    selectRoles.Add(cListBoxRoleNames.Items[i].ToString());
                }
            }

            if (Item != null)
            {
                Item.EmailAddress = textBoxEmailAddress.Text;
                Item.FullName = textBoxSurname.Text + textBoxName.Text;
                Item.IsActive = cBoxIsActive.Checked;
                Item.Name = textBoxName.Text;
                Item.RoleNames = selectRoles.ToArray();
                Item.Surname = textBoxSurname.Text;
                Item.UserName = textBoxUserName.Text;
                string jsons = JsonConvert.SerializeObject(Item);
                result = Client.Put(url + act, jsons);
            }
            else
            {
                CreateUserDto dto = new CreateUserDto();
                dto.EmailAddress = textBoxEmailAddress.Text;
                dto.IsActive = cBoxIsActive.Checked;
                dto.Name = textBoxName.Text;
                dto.RoleNames = selectRoles.ToArray();
                dto.Surname = textBoxSurname.Text;
                dto.UserName = textBoxUserName.Text;
                dto.Password = textBoxPassword.Text;
                string jsons = JsonConvert.SerializeObject(dto);
                result = Client.Post(url + act, jsons);
            }
            if (Utils.ExceptionHandler(result) == null)
            {
                Utils.SysMsg("保存成功！");
                var resp = Utils.SuccessHandler(result);
                Item = JsonConvert.DeserializeObject<UserDto>(resp.ToString());
                LoadData();
            }
        }

        private void NewToolStripButton_Click(object sender, EventArgs e)
        {
            ResetForm();
            saveToolStripButton.Enabled = true;
            textBoxPassword.Enabled = true;
        }

        private void ResetForm()
        {
            if (Item != null)
            {
                textBoxUserName.Text = "";
                textBoxEmailAddress.Text = "";
                textBoxName.Text = "";
                textBoxPassword.Text = "";
                textBoxSurname.Text = "";
                Item = null;
            }
        }

        private void DelToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (Item != null)
                {
                    string act = string.Format(url + "Delete?Id={0}", Item.Id);
                    string result = Client.Delete(act);
                    if (Utils.ExceptionHandler(result) == null)
                    {
                        ResetForm();
                        LoadData();
                        saveToolStripButton.Enabled = false;
                        copyToolStripButton.Enabled = false;
                    }
                }
            }
        }

        private void CopyToolStripButton_Click(object sender, EventArgs e)
        {
            if (Item != null)
            {
                string act = url + "Create";
                CreateUserDto dto = new CreateUserDto();                
                dto.IsActive = false;
                dto.Name = Item.Name;
                dto.RoleNames = Item.RoleNames;
                dto.Surname = Item.Surname;
                dto.UserName = Item.UserName + "Copy";
                dto.Password = "123456";
                dto.EmailAddress = dto.UserName + "@example.com";
                string jsons = JsonConvert.SerializeObject(dto);
                string result = Client.Post(act, jsons);
                if (Utils.ExceptionHandler(result) == null)
                {
                    Utils.SysMsg("复制成功！初始密码为：123456");
                }
                LoadData();
            }
        }

        private void DataGridViewM_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Item = dataGridViewM.CurrentRow.DataBoundItem as UserDto;
            if (Item != null)
            {
                textBoxUserName.Text = Item.UserName;
                textBoxEmailAddress.Text = Item.EmailAddress;
                textBoxName.Text = Item.Name;
                textBoxSurname.Text = Item.Surname;
                cBoxIsActive.Checked = Item.IsActive;

                for (int i = 0; i < cListBoxRoleNames.Items.Count; i++)
                {
                    bool chk = Item.RoleNames.Contains(cListBoxRoleNames.Items[i].ToString().ToUpper());
                    cListBoxRoleNames.SetItemChecked(i, chk);
                }
                saveToolStripButton.Enabled = true;
                copyToolStripButton.Enabled = true;
            }
        }
    }
}
